<template>
  <div class='articles-container'>
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <el-form :inline="true" class="demo-form-inline" :model="formInline">
          <el-form-item label="关键字" class="el-form-item-search">
            <el-input placeholder="根据文章标题搜索" v-model="formInline.keyword"></el-input>
          </el-form-item>
          <el-form-item label="状态" class="el-form-item-search">
            <el-select placeholder="请选择" v-model="formInline.state">
              <el-option label="启用" value="1"></el-option>
              <el-option label="禁用" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button size="medium" @click="clearForm">清除</el-button>
            <el-button type="primary" size="medium" @click="changepageSearch">搜索</el-button>
          </el-form-item>
          <el-form-item class="el-button-add" >
            <el-button type="success" size="small" icon="el-icon-edit" @click="openAddDialog('add')">新增技巧</el-button>
          </el-form-item>
        </el-form>
        <el-alert
          :title="alertTitle"
          type="info"
          show-icon>
        </el-alert>
        <el-table :data="list">
          <el-table-column label="序号" type="index"/>
          <el-table-column label="文章标题" prop="title" >
            <template #default="{ row }">
              {{ row.title }}
              <span v-if="row.videoURL" class="el-icon-film" style="color: #4238FF; font-size: 18px;cursor: pointer;" @click="openVideo(row)"></span>
            </template>
          </el-table-column>
          <el-table-column label="阅读数" prop="visits" />
          <el-table-column label="录入人" prop="username" />
          <el-table-column label="录入时间" prop="createTime" >
            <template #default="{ row }">
              {{ row.createTime | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="state" >
            <template #default="{ row }">
              <span v-if="row.state === 1">已启用</span>
              <span v-else>已禁用</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button size="small" type="text" @click="showPreviewDialog(row)">预览</el-button>
              <el-button v-if="row.state === 0" size="small" type="text" @click="changeState(row)">启用</el-button>
              <el-button v-else size="small" type="text" @click="changeState(row)">禁用</el-button>
              <el-button :disabled="row.state === 1" size="small" type="text" @click="openAddDialog('edit',row)">修改</el-button>
              <el-button :disabled="row.state === 1" size="small" type="text" @click="delArticle(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="height: 60px; margin-top: 10px;float: right;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="pageSize"
          layout="prev, pager, next, sizes, jumper"
          :total="total"
          v-show="total>=pageSize"
          background>
        </el-pagination>
        </div>
      </el-card>
    </div>
    <el-dialog
      class="add-dialog"
      :title="title"
      :visible.sync="showaddDialog"
      @close="closeaddDialog"
      width="800px">
      <el-form :model="adddialogForm" :rules="rules" ref="adddialogForm">
        <el-form-item label="文章标题:" prop="title" label-width="90px">
          <el-input placeholder="请输入文章标签" v-model="adddialogForm.title"></el-input>
        </el-form-item>
        <el-form-item label="文章内容:" label-width="90px" prop="articleBody" ref="articleBody">
          <quill-editor
          style="min-height: 200px;"
          :options="editorOption"
          v-model="adddialogForm.articleBody"
          ></quill-editor>
        </el-form-item>
        <el-form-item label="视频地址:" prop="videoURL" label-width="90px">
          <el-input placeholder="请输入视频地址" v-model="adddialogForm.videoURL"></el-input>
        </el-form-item>
      </el-form>
      <template>
        <div style="text-align: right;">
          <el-button @click="closeaddDialog">取消</el-button>
          <el-button type="primary" @click="addArticles">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      title="预览文章"
      :visible.sync="previewDialog"
      width="800px"
      >
      <div>
        <h2>{{previewForm.title}} </h2>
        <span>{{previewForm.createTime | formatDate}} </span>
        <span>{{previewForm.username}} </span>
        <span class="el-icon-view" style="margin-right: 3px;"></span>
        <span>{{previewForm.visits}} </span>
      </div>
      <div style="border-top: 1px dashed #CCCCCC;margin-top: 10px; background-color: #F5F5F5;padding: 15px 10px;">
        <p v-html="previewForm.articleBody">
        </p>
      </div>
    </el-dialog>
    <div class="video-preview" v-if="showVideo">
      <div class="video-box">
        <span class="el-icon-close" @click="closeVideo"></span>
        <video :src="videoURL" class="video" autoplay></video>
      </div>
    </div>
  </div>
</template>

<script>
import { list, add, detail, update, remove, changeState } from '@/api/hmmm/articles'
// import { formatDate } from '@/filters/index'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  ['blockquote'], // 引用  代码块-----['blockquote', 'code-block']
  ['code-block', 'image', 'link'] // 链接、图片、视频-----
]

export default {
  components: {
    quillEditor
  },
  data () {
    return {
      videoURL: '',
      showVideo: false,
      str: 'add',
      previewDialog: false,
      editorOption: {
        theme: 'snow',
        modules: {
          toolbar: toolbarOptions
        },
        placeholder: ''
      },
      showaddDialog: false,
      pageSize: 10,
      total: 0,
      page: 1,
      list: [],
      formInline: {
        keyword: '',
        state: ''
      },
      previewForm: {
        title: '',
        createTime: '',
        username: '',
        visits: 0,
        articleBody: ''
      },
      adddialogForm: {
        title: '',
        articleBody: '',
        videoURL: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: ['blur', 'change'] }
        ],
        articleBody: [
          { required: true, message: '请输入文章内容', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  created () {
    this.getlist()
  },
  computed: {
    title () {
      if (this.str === 'add') return '添加文章'
      return '修改文章'
    },
    alertTitle () {
      return `数据一共${this.total}条`
    }
  },
  methods: {
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.page = 1
      this.pageSize = val
      if (this.formInline.keyword !== '' || this.formInline.state !== '') {
        // console.log(this.page, this.pageSize)
        this.getListByKeyword()
        return
      }
      this.getlist()
    },
    handleCurrentChange (newPage) {
      this.page = newPage
      // console.log(newPage)
      if (this.formInline.keyword !== '' || this.formInline.state !== '') {
        this.getListByKeyword()
        return
      }
      this.getlist()
    },
    async getlist () {
      const res = await list({ page: this.page, pagesize: this.pageSize })
      // console.log(res)
      // if (res.data.items.createTime) {
      //   res.data.items.createTime = parseTime(res.data.items.createTime)
      // }
      // res.data.items.forEach(item => {
      //   if (item.state === 0) {
      //     item.state = '已禁用'
      //   } else {
      //     item.state = '已启用'
      //   }
      // })
      this.total = res.data.counts
      this.list = res.data.items
    },
    clearForm () {
      this.formInline = {
        keyword: '',
        state: ''
      }
      this.getlist()
    },
    changepageSearch () {
      this.page = 1
      this.getListByKeyword()
    },
    async getListByKeyword () {
      let res
      // console.log(this.page, this.pageSize)
      if (this.formInline.keyword !== '' && this.formInline.state === '') {
        res = await list({ page: this.page, pagesize: this.pageSize, keyword: this.formInline.keyword })
      } else if (this.formInline.keyword === '' && this.formInline.state !== '') {
        res = await list({ page: this.page, pagesize: this.pageSize, state: this.formInline.state })
      } else {
        res = await list({ page: this.page, pagesize: this.pageSize, keyword: this.formInline.keyword, state: this.formInline.state })
      }
      // console.log(res)
      // res.data.items.forEach(item => {
      //   if (item.state === 0) {
      //     item.state = '已禁用'
      //   } else {
      //     item.state = '已启用'
      //   }
      // })
      // console.log(res)
      this.total = res.data.counts
      this.list = res.data.items
    },
    async changeState (row) {
      // state = !state
      // console.log(row)
      if (row.state === 1) {
        row.state = 0
      } else {
        row.state = 1
      }
      await changeState(row)
      this.$message.success('操作成功')
      // this.getListByKeyword()
      // this.getlist()
    },
    articleBodyChangeFn () {
      this.$refs.articleBody.resetField()
    },
    closeaddDialog () {
      this.showaddDialog = false
      this.adddialogForm = {
        title: '',
        articleBody: '',
        videoURL: ''
      }
      this.$refs.adddialogForm.resetFields()
      this.articleBodyChangeFn()
    },
    addArticles () {
      this.$refs.adddialogForm.validate(async flag => {
        if (!flag) return this.$message.warning('请填写完整表单内容')
        if (this.str === 'add') {
          await add(this.adddialogForm)
        } else {
          await update(this.adddialogForm)
        }
        this.$message.success('操作成功')
        this.closeaddDialog()
        this.page = 1
        this.getlist()
        // console.log(res)
      })
    },
    async showPreviewDialog (row) {
      this.previewDialog = true
      // console.log(row)
      const res = await detail(row)
      // console.log(res)
      this.previewForm = res.data
      this.previewForm.username = row.username
    },
    async openAddDialog (str, row) {
      this.showaddDialog = true
      this.str = str
      if (str === 'edit') {
        const res = await detail(row)
        // console.log(res)
        this.adddialogForm = res.data
      }
    },
    delArticle (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        type: 'warning'
      }).then(async () => {
        await remove(row)
        this.$message.success('删除成功!')
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.getlist()
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    openVideo (row) {
      this.showVideo = true
      this.videoURL = row.videoURL
    },
    closeVideo () {
      this.showVideo = false
    }
  }
}
</script>

<style scoped lang="scss">
.el-form-item-search {
  margin-left: 30px;
}
.el-button-add {
  position: absolute;
  right: 30px;
}
.video-preview{
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.3);
  z-index: 10;
  // overflow: hidden;
  .video-box {
    width: 800px;
    height: 600px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
    z-index: 20;
    // background: red;
    .el-icon-close {
      width: 50px;
      height: 50px;
      position: absolute;
      top: 10px;
      left: 50%;
      transform: translate(-50%);
      background: rgba(0,0,0,0.4);
      border-radius: 50%;
      text-align: center;
      line-height: 50px;
      font-size: 20px;
      color: #fff;
    }
    .video {
      margin-top: 80px;
      // position: absolute;
      // top: 110px;
      width: 100%;
      height: 100%;
      // background: pink;
    }
  }
}
::v-deep .ql-editor {
  min-height: 200px;
}
</style>
